import MobileSelect, { CascadeData } from 'mobile-select';
import { useEffect, useRef, useState } from 'react';

interface Props {
  iccid?: string;
  iccidList: any;
  onChange: (v: any) => void;
}

export default function MIccidPicker({ iccid, iccidList, onChange }: Props) {
  const iccidRef = useRef<MobileSelect | null>(null);
  const [select, setSelect] = useState(false);

  // 将滚轮回滚到选择的数据
  useEffect(() => {
    if (iccidRef.current && iccid) {
      let pidx = (iccidList ?? []).findIndex((item: { iccid: string }) => item.iccid === iccid);
      iccidRef.current.locatePosition(0, pidx);
    }
  }, [iccid]); //eslint-disable-line

  function handleRef(v?: any) {
    if (iccidRef.current) {
      iccidRef.current.updateWheel(0, iccidList);
      return;
    }
    let data = [{ iccid: '暂无可选卡号', id: '暂无可选卡号', children: '' }];
    iccidRef.current = new MobileSelect({
      trigger: '#m-iccid-picker',
      title: '卡号选择',
      wheels: [{ data }],
      keyMap: { id: 'id', value: 'iccid', childs: 'children' },
      onChange: (cur: any) => {
        if (!select) {
          setSelect(true);
        }
        // if (cur.length) {
        //   onChange(iccidList.find((i) => i.iccid === cur[0].iccid));
        // }
        onChange((cur as CascadeData[]).map((i) => (i as CascadeData)?.iccid));
      },
    });
  }

  return (
    <div id="m-iccid-picker" className={`value ${select ? '' : 'place-holder'}`} ref={(v) => handleRef(v)}>
      {!!iccid ? iccid : '请选择需要更换的卡号'}
    </div>
  );
}
